import requests as req;
import os;

if __name__ == '__main__':

    if(not os.path.exists("bug_file")):
        os.mkdir("bug_file");

    cname = input("请选择您想要爬取的城市名:\n");
    # keyword = input("请选择您想要爬取的门店名称或地址:\n");

    url = "http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword";
    params = {
        "cname":cname,
        "pid":"",
        "keyword":"",
        "pageIndex":1,
        "pageSize":2000
    };


    # UA伪装
    header = {
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36",
        "Mobile-User-Agent":"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Mobile Safari/537.36"
    }


    result = req.post(url,params=params,headers=header);
    json = result.json();

    if json.get("Table")[0].get("rowcount") > 0:

        file_name = "爬虫-肯德基门店-" + cname + ".txt";
        with open("./bug_file/"+file_name, "w", encoding="utf-8") as wf:
            for item in json.get("Table1"):
                wf.write(str(item) + "\n");

        print(file_name, "爬取完毕!!");
        print(f'{cname}地区共有{json.get("Table")[0].get("rowcount")}家连锁店');

    else:
        print("爬取失败!!", json.get("errno"));

